import time
from enum import Enum
from functools import wraps

from utils.logger import Logger


class AppStatus(Enum):
    """
    自定义状态码枚举类
    """
    Success = (1000, "成功")
    UnknownError = (1001, "未知错误")


class AppException(Exception):
    def __init__(self, status, detail):
        self.status = status
        self.detail = detail

    def __str__(self):
        error_info = f"{self.status.value[0]}: {self.status.value[1]} - {self.detail}"
        return error_info

    def __repr__(self):
        return self.__str__()



def response(status: AppStatus = AppStatus.Success, detail="", data=None):
    return {
        "status_code": status.value[0],
        "message": status.value[1],
        "detail": detail,
        "data": data
    }


def error_decorator(action):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            Logger.info(f"Action: {action}. Start: {start_time}")
            try:
                result = func(*args, **kwargs)
            except AppException as e:
                Logger.exception(e)
                return response(
                    status=e.status,
                    detail=e.detail
                )
            except Exception as e:
                Logger.exception(e)
                return response(
                    status=AppStatus.UnknownError,
                    detail=str(e)
                )
            finally:
                end_time = time.time()
                elapsed_time = end_time - start_time
                Logger.info(f"Action: {action}. End: {end_time}. Elapsed: {elapsed_time}")
            return result
        return wrapper
    return decorator
